package com.baiyue.admin.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.baiyue.admin.entity.AdminInfo;
import com.baiyue.admin.manage.AdminInfoManage;

@Controller
public class LoginAct {
  
	public static final int STATUS_EMPTY = 0;
	public static final int STATUS_NO_SUCH_ADMIN = 1;
	public static final int STATUS_PASSWORD_NOTRIGHT = 2;
	public static final int STATUS_SUCCESS = 3;
	
	@Autowired
	private AdminInfoManage adminInfoManage;
	
	
	@RequestMapping("login.do")
	public void loginVaridation(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		String adminName = (String) req.getParameter("adminName");
		String password  = (String) req.getParameter("password");
		
		System.out.println("login:"+adminName+":"+password);
		
		resp.setContentType("text/json;chartset=uft-8");
		String jsonString = "{code:%d}";
		if(adminName == null || password == null ){
			resp.getWriter().write(String.format(jsonString, STATUS_EMPTY));
			return;
		}
		AdminInfo adminInfo = adminInfoManage.getAdminInfoByName(adminName);
		if(adminInfo == null) {
			resp.getWriter().write(String.format(jsonString, STATUS_NO_SUCH_ADMIN));
			return;
		}
		if(!password.equals(adminInfo.getPassword())){
			resp.getWriter().write(String.format(jsonString, STATUS_PASSWORD_NOTRIGHT));
			return;
		} else {
			req.getSession().setAttribute("adminInfo", adminInfo);
			resp.getWriter().write(String.format(jsonString, STATUS_SUCCESS));
			//保存在session里面
			req.getSession().setAttribute("adminInfo", adminInfo);
			return;
		}
	}
	
    @RequestMapping("loginSuccess.do")
    public ModelAndView loginSuccess(){
		return new ModelAndView(new RedirectView("index.jsp"));
    }
}
